package main

import (
	"context"
	"flag"
	"fmt"
	"os"
	"path/filepath"
	"ssh_status/internal/v2/core"
	"ssh_status/internal/v2/log"
	"ssh_status/internal/v2/scanner"
	"ssh_status/internal/v2/web"
	"time"
)

func main() {
	// 命令行参数
	network := flag.String("network", "", "要扫描的网段 (CIDR格式，如192.168.1.0/24)")
	username := flag.String("username", "", "SSH用户名")
	password := flag.String("password", "", "SSH密码")
	threads := flag.Int("threads", 100, "并发线程数")
	output := flag.String("output", ".", "输出目录")
	debug := flag.Bool("debug", false, "是否启用调试模式")
	logLevel := flag.Int("log-level", int(log.LevelInfo), "日志级别 (0:DEBUG, 1:INFO, 2:WARN, 3:ERROR)")
	enableWeb := flag.Bool("web", false, "启用Web服务器")
	webPort := flag.String("port", "8080", "Web服务器监听端口")

	flag.Parse()

	// 初始化日志系统
	logger := log.NewLogger(log.LogLevel(*logLevel))
	if *debug {
		logger.SetLevel(log.LevelDebug)
	}
	log.SetDefaultLogger(logger)

	log.Debug("调试模式已启用")
	log.Info("程序启动")
	log.Info("命令行参数: network=%s, username=%s, web=%v", *network, *username, *enableWeb)

	// 命令行模式参数验证
	if !*enableWeb {
		if *network == "" {
			log.Error("必须指定要扫描的网段")
			flag.Usage()
			os.Exit(1)
		}

		if *username == "" {
			log.Error("必须指定SSH用户名")
			flag.Usage()
			os.Exit(1)
		}

		if *password == "" {
			log.Error("必须指定SSH密码")
			flag.Usage()
			os.Exit(1)
		}
	}

	// 创建输出目录
	outputPath, err := filepath.Abs(*output)
	if err != nil {
		log.Error("解析输出路径失败: %v", err)
		os.Exit(1)
	}

	if err := os.MkdirAll(outputPath, 0755); err != nil {
		log.Error("创建输出目录失败: %v", err)
		os.Exit(1)
	}

	if *enableWeb {
		// Web模式: 初始化Web服务器
		webServer := web.NewServer()
		addr := ":" + *webPort
		log.Info("启动Web服务器，监听地址: %s", addr)
		fmt.Println("Web服务器已启动，访问地址: http://localhost" + addr)
		if err := webServer.Start(addr); err != nil {
			log.Error("Web服务器启动失败: %v", err)
			os.Exit(1)
		}
	} else {
		// 命令行模式: 初始化扫描器
		config := core.ScannerConfig{
			Network:   *network,
			Username:  *username,
			Password:  *password,
			Threads:   *threads,
			OutputDir: outputPath,
			Debug:     *debug,
			LogLevel:  *logLevel,
		}

		s, err := scanner.NewScanner(config)
		if err != nil {
			log.Error("创建扫描器失败: %v", err)
			os.Exit(1)
		}
		defer s.Close()

		ctx := context.Background()
		if err := s.Initialize(ctx); err != nil {
			log.Error("初始化扫描器失败: %v", err)
			os.Exit(1)
		}

		// 运行扫描
		log.Info("开始扫描网段: %s", *network)
		startTime := time.Now()

		success, sudo, portFailed, authFailed, err := s.Run(ctx)
		if err != nil && err != context.Canceled {
			log.Error("扫描失败: %v", err)
			os.Exit(1)
		}

		// 打印结果
		duration := time.Since(startTime)
		log.Info("扫描完成! 用时: %v", duration)
		log.Info("SSH连接成功: %d", len(success))
		log.Info("SSH连接成功(可sudo): %d", len(sudo))
		log.Info("SSH端口连接失败: %d", len(portFailed))
		log.Info("SSH认证失败: %d", len(authFailed))
	}
}
